package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.config.QiniuConfiguration;
import com.itheima.health.constant.RedisConstant;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import com.itheima.health.util.IdWorker;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @description 套餐控制器
 **/
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetMealController {

    @Autowired
    private SetMealService setMealService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    QiniuConfiguration qiniuConfiguration;

    /**
     * 上传图片
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile multipartFile) {
        log.info("文件上传，name:{},size:{}", multipartFile.getOriginalFilename(), multipartFile.getSize());
        //原始文件名
        String originalFileName = multipartFile.getOriginalFilename();
        //使用UUID构造不重复的文件名
//        String fileName = UUID.randomUUID().toString().replace("-", "") + "_" + originalFileName;
        IdWorker idWorker = IdWorker.getIdWorker(0,0);
        long nowTime = idWorker.nextId();
        String fileName = nowTime + "." + originalFileName.substring(originalFileName.lastIndexOf(".") + 1);;
        System.out.println(fileName);

        QiniuUtils qiniuUtils = qiniuConfiguration.qiniuUtils();
        //获取输入流并上传
        try (InputStream is = multipartFile.getInputStream()) {
            qiniuUtils.upload2Qiniu(is, fileName);
        } catch (IOException e) {
            log.error("", e);
            return new Result(false, MessageConst.PIC_UPLOAD_FAIL);
        }

        //构造返回值
        String pic = qiniuUtils.getUrlPrefix() + fileName;

        //将上传图片名称存入Redis，基于Redis的Set集合存储
        SetOperations setOperations = this.redisTemplate.opsForSet();
        setOperations.add(RedisConstant.SETMEAL_PIC_RESOURCES, fileName);

        return new Result(true, MessageConst.PIC_UPLOAD_SUCCESS, pic);
    }

    /**
     * 添加套餐
     *
     * @param setmeal       套餐基本信息
     * @param checkgroupIds 检查组ID列表
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {
        log.info("[套餐-添加]data:{},checkgroupIds:{}", setmeal, checkgroupIds);
        QiniuUtils qiniuUtils = qiniuConfiguration.qiniuUtils();
        if (!StringUtils.isEmpty(setmeal.getImg())) {
            String img = setmeal.getImg().replace(qiniuUtils.getUrlPrefix(), "");
            setmeal.setImg(img);
        }
        //RPC调用添加数据
        setMealService.add(setmeal, checkgroupIds);


        SetOperations setOperations = this.redisTemplate.opsForSet();
        // 添加成功，要将有用的图片到redis集合中删除
//        setOperations.remove(RedisConstant.SETMEAL_PIC_List, setmeal.getImg());
        // 添加成功，要将保存在数据库中的图片名称添加redis集合中
        setOperations.add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

        return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS);
    }

    /**
     * 分页查询
     *
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(QueryPageBean queryPageBean) {
        //调用DAO层查询并返回
        PageResult pageResult = setMealService.findPage(queryPageBean);
        //构造返回结果并返回
        return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS, pageResult);
    }

    /**
     * 修改套餐
     *
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {
        // 获取原有图片的名称
        Setmeal setmealInDb = setMealService.findById(setmeal.getId().toString());
        // 调用服务更新
        setMealService.update(setmeal, checkgroupIds);
        SetOperations setOperations = this.redisTemplate.opsForSet();
        // 判断是否更改过图片
        if (!setmealInDb.getImg().equals(setmeal.getImg())) {
            //图片修改了，旧的就没用，就要删除
//            setOperations.remove(RedisConstant.SETMEAL_PIC_List, setmeal.getImg());
//            setOperations.add(RedisConstant.SETMEAL_PIC_List, setmealInDb.getImg());
            setOperations.remove(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmealInDb.getImg());
            setOperations.add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        }
        return new Result(true, MessageConst.EDIT_SETMEAL_SUCCESS);
    }

    /**
     * 根据id删除套餐
     *
     * @param id
     * @returnhttp://localhost:16080/api/setmeal/deleteSetmealById?id=56
     */
    @PostMapping("/deleteSetmealById")
    public Result deleteById(int id) {
        // 查一下图片名称
        Setmeal setmeal = setMealService.findById(String.valueOf(id));

        // 调用业务服务删除
        setMealService.deleteById(id);

        // 从redis，保存了数据库存放的图片集合中移除这个被删除的图片
        SetOperations setOperations = this.redisTemplate.opsForSet();
//        setOperations.add(RedisConstant.SETMEAL_PIC_List, setmeal.getImg());
        setOperations.remove(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

        return new Result(true, MessageConst.DELETE_SETMEAL_SUCCESS);
    }
}
